﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace EzFreamWork
{
    public class AudioControl : MonoBehaviour
    {
        public static AudioControl Instance;
        AudioClip audioClip;
        AudioSource audioSource;
        Dictionary<string, AudioClip> audioDic = new Dictionary<string, AudioClip>();
        Dictionary<string, AudioSource> BGM_Dic = new Dictionary<string, AudioSource>();
        GameObject BGM_Obj;
        private void Awake()
        {
            Instance = this;
        }

        /// <summary>
        /// 播放背景音乐
        /// </summary>
        public void PlayBGM(string path,AudioType audioType)
        {
            if (!BGM_Dic.ContainsKey(path))
            {
                GameObject go = new GameObject("BGM_Obj");
                BGM_Obj = GameObject.Instantiate(go, transform) as GameObject;
                BGM_Obj.AddComponent<AudioSource>();
                AudioSource audioSource = BGM_Obj.GetComponent<AudioSource>();
                BGM_Dic.Add(path, audioSource);
                BGM_Dic[path].Play();
                Debug.Log("Play");
            }
            else
            {
                BGM_Dic[path].Play();
            }
        }

        public void StopBgm()
        {
            foreach (var item in BGM_Dic)
            {
                item.Value.Stop();
            }
        }
        /// <summary>
        /// 根据路径加载音频
        /// </summary>
        /// <param name="path"></param>
        /// <param name="audioType"></param>
        public void PlayAudio(string path,AudioType audioType)
        {
            if (!audioDic.ContainsKey(path))//如果没有这个文件
            {
                StartCoroutine(LoadAudio(path, audioType));
            }
            else
            {
                audioClip = audioDic[path];
                audioSource.clip = audioClip;
                audioSource.Play();
            }
        }

        private IEnumerator LoadAudio(string recordPath, AudioType audioType = AudioType.WAV)
        {
            WWW www = new WWW(recordPath + AudioTypeToStr(audioType));
            Debug.Log("播放路径为" + recordPath + AudioTypeToStr(audioType));
            yield return www;
            audioClip = www.GetAudioClip();
            audioDic.Add(recordPath, audioClip);
            audioSource.clip = audioClip;
            audioSource.Play();
        }


        private string AudioTypeToStr(AudioType audioType)
        {
            switch (audioType)
            {
                case AudioType.MPEG:
                    return ".mp3";
                case AudioType.WAV:
                    return ".wav";
                default:
                    return ".wav";
            }
        }

        // Use this for initialization
        void Start()
        {
            //DontDestroyOnLoad(gameObject);
            audioSource = GetComponent<AudioSource>();
        }

    } 
}